<style scoped lang="less">
.white {
  background: #ffffff;
}
.oneCol {
  padding-top: 18px;
  .oneContain {
    width: calc(100% - 10px);
    height: 400px;
  }
}
.rowItem {
  border-top: 1px solid #eee;
  padding-top: 5px;
  min-height: 400px;
  .itemContain {
    display: flex;
    padding: 5px;
    .leftContain {
      flex: 0 0 80px;
      font-weight: bold;
      padding-top: 2px;
    }
    .rightContain {
      flex: 1;
    }
  }
}
.colRight {
  padding-top: 10px;
  border-left: 1px solid #eee;
  padding-left: 10px;
  padding-bottom: 10px;
}

</style>
<template>
  <div class="white">
    <Row :gutter="16">
      <Col span="24" class="oneCol">
      <div id="idOne" class="oneContain"></div>
      </Col>
    </Row>
    <Row class="rowItem">
      <Col span="12">
      <!-- 级别 -->
      <div class="itemContain">
        <div class="leftContain">对比级别：</div>
        <div class="rightContain">
          <RadioGroup v-model="queryObj.level">
            <Radio :label="item.value" v-for="(item,index) in levelList" :key="'level'+index"><span>{{item.text}}</span></Radio>
          </RadioGroup>
        </div>
      </div>
      <!-- 级别 -->
      <div class="itemContain">
        <div class="leftContain">能源类型：</div>
        <div class="rightContain">
          <RadioGroup v-model="queryObj.energy">
            <Radio :label="item.value" v-for="(item,index) in energyList" :key="'energy'+index"><span>{{item.text}}</span></Radio>
          </RadioGroup>
        </div>
      </div>
      <!-- 级别 -->
      <div class="itemContain">
        <div class="leftContain">时间粒度：</div>
        <div class="rightContain">
          <RadioGroup v-model="queryObj.granularity" @on-change="granularityChange()">
            <Radio :label="item.value" v-for="(item,index) in granularityList" :key="'granularity'+index"><span>{{item.text}}</span></Radio>
          </RadioGroup>
        </div>
      </div>
      <!-- 级别 -->
      <div class="itemContain">
        <div class="leftContain">时间范围：</div>
        <div class="rightContain">
          <DatePicker :type="queryObj.datetimerangeType" v-model="queryObj.dateValue" placeholder="选择时间范围" style="width: 100%;"></DatePicker>
        </div>
      </div>
      </Col>
      <Col span="12" class="colRight">
      <div> <span style="font-weight:bold;">对比对象：</span>
        <Tag type="dot" closable color="primary" v-for="(item,index) in spaceSelectData" :key="'space'+index" @on-close="spaceTagClick(item)">{{item.__label}}</Tag>
        <div>
          <Cascader ref="myCascader" :change-on-select="true" :render-format="cascaderFormat" :data="deviceSpaceData" @on-visible-change="visibleChange" @on-change="cascaderChange">
            <Button type="primary" shape="circle" icon="md-add"></Button>
          </Cascader>
        </div>
      </div>
      </Col>
      <Col span="24" style="text-align:center;padding-bottom:18px;">
      <Button type="primary" @click.native="carbon_comparison()">查询数据</Button>
      </Col>
    </Row>
  </div>
</template>
<script>
export default {
  data: function () {
    let nowDate = new Date()
    let yy = nowDate.getFullYear()
    let mm = nowDate.getMonth() + 1
    let dd = nowDate.getDate()
    mm = mm > 9 ? mm : '0' + mm
    dd = dd > 9 ? dd : '0' + dd
    let stime = yy + mm + '-01'
    let etime = yy + '-' + mm + '-' + dd
    return {
      value13: '',
      levelList: [{
        value: '1',
        text: '工厂'
      }, {
        value: '2',
        text: '车间'
      }, {
        value: '3',
        text: '生产线'
      }, {
        value: '4',
        text: '设备'
      }],
      energyList: [{
        value: '1',
        text: '碳排'
      }, {
        value: '2',
        text: '单车碳排'
      }, {
        value: '3',
        text: '电'
      }, {
        value: '4',
        text: '蒸汽'
      }, {
        value: '5',
        text: '压缩空气'
      }, {
        value: '6',
        text: '水'
      }, {
        value: '7',
        text: '冷量'
      }],
      granularityList: [{
        value: '1',
        text: '年'
      }, {
        value: '2',
        text: '月'
      }, {
        value: '3',
        text: '日'
      }, {
        value: '4',
        text: '时'
      }, {
        value: '5',
        text: '分'
      }, {
        value: '6',
        text: '秒'
      }],
      queryObj: {
        level: '1',
        energy: '1',
        granularity: '3',
        datetimerangeType: 'daterange',
        dateValue: [stime, etime]
      },
      oneChart: null,
      dateTypeData: [{
        key: '1',
        dateType: 'year',
        style: 'yyyy'
      }, {
        key: '2',
        dateType: 'month',
        style: 'yyyy-MM'
      }, {
        key: '3',
        dateType: 'daterange',
        style: 'yyyy-MM-dd'
      }, {
        key: '4',
        dateType: 'datetimerange',
        style: 'yyyy-MM-dd HH:mm:ss'
      }, {
        key: '5',
        dateType: 'datetimerange',
        style: 'yyyy-MM-dd HH:mm:ss'
      }, {
        key: '6',
        dateType: 'datetimerange',
        style: 'yyyy-MM-dd HH:mm:ss'
      }],
      deviceSpaceData: [],
      treeDataTem: [],
      treeData: [],
      spaceSelectData: [],
      spaceSelectTem: []
    }
  },
  mounted: function () {
    let self = this
    self.oneChart = self.$echarts.init(document.getElementById('idOne'))
    self.carbon_comparison()
    window.onresize = function () {
      self.oneChart.resize()
    }
    // 左边菜单折叠时触发
    window.vm.$on('iconRotateClick', function (data) {
      setTimeout(function () {
        if (self.oneChart) {
          self.oneChart.resize()
        }
      }, 600)
    })
    // 获取空间树数据
    self.list()
  },
  destroyed: function () {
    window.onresize = null
    this.oneChart = null
  },
  updated: function () {},
  methods: {
    drawEcharts: function (id, option) {
      let self = this
      // 基于准备好的dom，初始化echarts实例
      let myChart = self.$echarts.init(document.getElementById(id))
      // 绘制图表
      myChart.setOption(option)
      myChart.resize()
    },
    oneInit: function (chartData) {
      let self = this
      self.oneChart.showLoading({ text: '' })
      let seriesData = []
      let levelText = self.getKeyValue(self.levelList, 'value', self.queryObj.level, 'text')
      for (let i = 0; i < chartData.yaxises.length; i++) {
        let obj = {
          name: levelText + (i + 1),
          type: 'line',
          smooth: true,
          data: chartData.yaxises[i],
          itemStyle: {
            normal: {
              color: self.randomHexColor()
            }
          }
        }
        seriesData.push(obj)
      }
      let option = {
        title: {
          text: self.getKeyValue(self.energyList, 'value', self.queryObj.energy, 'text'),
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: { show: true }
          },
          right: 40
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          data: chartData.xaxis
        }],
        yAxis: [{
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        }],
        series: seriesData
      }
      if (!self.oneChart) {
        self.oneChart = self.$echarts.init(document.getElementById('idOne'))
      }
      // 绘制图表
      self.oneChart.setOption(option)
      self.oneChart.hideLoading()
    },
    // 能源监控--对比
    carbon_comparison: function () {
      let self = this
      let stime = ''
      let etime = ''
      if (self.queryObj.dateValue instanceof Array) {
        stime = self.queryObj.dateValue[0] ? self.queryObj.dateValue[0] : ''
        etime = self.queryObj.dateValue[1] ? self.queryObj.dateValue[1] : ''
        if (stime !== '' && stime !== undefined) {
          let str = self.queryObj.granularity === '3' ? 'yyyy-mm-dd' : 'yyyy-mm-dd h:m:s'
          stime = self.dateFormat(stime, str)
        }
        if (etime !== '' && etime !== undefined) {
          let str = self.queryObj.granularity === '3' ? 'yyyy-mm-dd' : 'yyyy-mm-dd h:m:s'
          etime = self.dateFormat(etime, str)
        }
      }
      let spaceTargetIds = []
      self.spaceSelectData.forEach((item) => {
        spaceTargetIds.push(item.id)
      })
      let jsonStr = JSON.stringify({
        level: self.getKeyValue(self.levelList, 'value', self.queryObj.level, 'text'),
        energy: self.getKeyValue(self.energyList, 'value', self.queryObj.energy, 'text'),
        granularity: self.getKeyValue(self.granularityList, 'value', self.queryObj.granularity, 'text'),
        stime: stime,
        etime: etime,
        target: spaceTargetIds.join(',')
      })
      let postData = {
        json: jsonStr
      }
      self.oneChart.showLoading({ text: '' })
      window.myapi.carbon_comparison(postData).then(function (res) {
        if (res.status === 200) {
          self.oneInit(res.data.data)
        } else {
          self.$Message.error('请求数据失败!')
        }
        self.oneChart.hideLoading()
      }).catch(function (e) {
        self.$Message.error('请求数据失败!')
        self.oneChart.hideLoading()
      })
    },
    // 时间粒度改变
    granularityChange: function () {
      let self = this
      if (self.queryObj.granularity === '1') {
        self.queryObj.datetimerangeType = 'year'
        self.queryObj.dateValue = ''
      } else if (self.queryObj.granularity === '2') {
        self.queryObj.datetimerangeType = 'month'
        self.queryObj.dateValue = ''
      } else {
        // 时间范围的值是数组
        self.queryObj.dateValue = []
        for (let i = 0; i < self.dateTypeData.length; i++) {
          if (self.dateTypeData[i].key === self.queryObj.granularity) {
            self.queryObj.datetimerangeType = self.dateTypeData[i].dateType
          }
        }
      }
    },
    // yyyy-mm-dd
    dateFormat: function (str, format) {
      let nowDate = new Date(str)
      let yy = nowDate.getFullYear()
      let mm = nowDate.getMonth() + 1
      let dd = nowDate.getDate()
      let h = nowDate.getHours()
      let m = nowDate.getMinutes()
      let s = nowDate.getSeconds()
      mm = mm > 9 ? mm : '0' + mm
      dd = dd > 9 ? dd : '0' + dd
      h = h > 9 ? h : '0' + h
      m = m > 9 ? m : '0' + m
      s = s > 9 ? s : '0' + s
      if (format === 'yyyy-mm-dd') {
        return yy + '-' + mm + '-' + dd
      } else {
        return yy + '-' + mm + '-' + dd + ' ' + h + ':' + m + ':' + s
      }
    },
    // key to text
    key2text: function (key, arr) {
      for (let i = 0; i < arr.length; i++) {
        if (key === arr[i].value) {
          return arr[i].text
        }
      }
    },
    // 随机生成十六进制颜色
    randomHexColor: function () {
      var hex = Math.floor(Math.random() * 16777216).toString(16) // 生成ffffff以内16进制数
      while (hex.length < 6) { // while循环判断hex位数，少于6位前面加0凑够6位
        hex = '0' + hex
      }
      return '#' + hex // 返回‘#'开头16进制颜色
    },
    // 树 数据list
    list: function () {
      let self = this
      let getData = {
        'size': 20,
        'page': self.pageIndex,
        'searchParam': self.queryStr
      }
      window.myapi.space_list(getData).then(function (res) {
        if (res.data.status === 200) {
          self.treeDataTem = res.data.data.content
          self.treeReady(res.data.data.content)
        } else {
          let msg = res.data.msg ? res.data.msg : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
        }
      }).catch(function (e) {
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
        }
      })
    },
    // 级联选择 处理为标准格式
    treeReady: function (arr) {
      let self = this
      self.treeData = []
      let one = self.treeRoot(arr)
      self.treeData.push(one)
      // 级联选择 格式标准化处理
      self.deviceSpaceData = self.deviceSpaceStandard(self.treeData)
    },
    // 级联选择 提取树 根节点
    treeRoot: function (arr) {
      let self = this
      let len = arr.length
      for (let i = 0; i < len; i++) {
        if (arr[i].parentId === 0) {
          arr[i].children = []
          return self.treeNode(arr, arr[i])
        }
      }
    },
    // 级联选择 提取树 子节点
    treeNode: function (arr, one) {
      let self = this
      let len = arr.length
      one.children = []
      for (let i = 0; i < len; i++) {
        if (one.id === arr[i].parentId) {
          arr[i].children = []
          one.children.push(self.treeNode(arr, arr[i]))
        }
      }
      return one
    },
    // 设备控件级联菜单数据 标准化处理
    deviceSpaceStandard: function (arr) {
      let self = this
      let len = arr.length
      let temArr = []
      for (let i = 0; i < len; i++) {
        let one = {
          value: arr[i].id,
          label: arr[i].name,
          id: arr[i].id,
          parentId: arr[i].parentId,
          children: self.deviceSpaceStandard(arr[i].children)
        }
        temArr.push(one)
      }
      return temArr
    },
    // 自定义 级联菜单显示
    cascaderFormat: function (labels, selectedData) {
      let self = this
      const index = labels.length - 1
      if (selectedData.length > 0) {
        // 避免不是最后的子级，点击空白处，值获取问题
        let labelArray = []
        selectedData.forEach(item => {
          labelArray.push(item.label)
        })
        let last = selectedData.length -1
        selectedData[last].__label = labelArray.join('/')
        this.spaceSelectTem = selectedData
      }
      return labels[index]
    },
    // 级联菜单显示隐藏
    visibleChange: function (data) {
      if (!data) {
        // 隐藏时，添加末尾选装的数据
        if (this.spaceSelectTem.length > 0) {
          let i = this.spaceSelectTem.length -1
          let item = this.spaceSelectTem[i]
          this.spaceSelectData = this.$utils.arrayPush(this.spaceSelectData, item, 'id')
        }
      }
    },
    // 选择完成后的回调，返回值 value 即已选值 value，selectedData 为已选项的具体数据
    cascaderChange: function (value, selectedData) {
      // 选中的所有值
      this.spaceSelectTem = selectedData
    },
    getKeyValue: function (arr, key, value, key2) {
      let self = this
      let str = ''
      arr.forEach((item) => {
        if (String(value) === String(item[key])) {
          str = item[key2]
        }
      })
      return str
    },
    // 显示的空间tag删除单击
    spaceTagClick: function (item) {
      this.spaceSelectData = this.$utils.arrayDelete(this.spaceSelectData, item, 'id')
    }
  }
}

</script>
